// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const fs = require('fs')
const path = require('path')
const middleware = require('./middleware')

// 批量引入modules
function getModules() {
  // 需要批量引入的目录
  const modules = {}
  // 根目录路径
  const baseDir = path.join(__dirname, 'modules')
  // 遍历子目录
  const subDirs = fs.readdirSync(baseDir)
  subDirs.forEach((subDir) => {
    const subDirPath = path.join(baseDir, subDir)
    if (fs.statSync(subDirPath).isDirectory()) {
      const moduleFilePath = path.join(subDirPath, 'index.js')
      if (fs.existsSync(moduleFilePath)) {
        const tempModules = require(moduleFilePath)
        for (let key in tempModules) {
          modules[key] = tempModules[key]
        }
      }
    }
  })
  return modules
}

const MoAdmin = {
  async _before() {
    // 挂载中间件
    this.middleware = {}
    for (const mwName in middleware) {
      this.middleware[mwName] = middleware[mwName].bind(this)
    }

    // 校验token，并挂载权限信息到 this.authInfo
    await this.middleware.validateToken()

    // 权限控制
    await this.middleware.accessControl()
  },

  /**
   * 后置处理器
   * @param {Object} err 错误
   * @param {Object} res 结果
   */
  _after(err, res) {
    if (err) throw err

    //剔除多余字段
    delete res.token
    delete res.tokenExpired

    return res
  }
}

// 注册所有模块
const moAdminModules = getModules()
for (const fnName in moAdminModules) {
  MoAdmin[fnName] = moAdminModules[fnName]
}

module.exports = MoAdmin
